package cn.fjc920.siaa.fragments

import android.content.DialogInterface
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activitys.AboutActivity
import cn.fjc920.siaa.activitys.HomePageActivity
import cn.fjc920.siaa.activitys.SettingsActivity
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import cn.fjc920.siaa.internetUtils.OkhttpUtils.DataCallBack
import kotlinx.android.synthetic.main.fragment_my.*
import kotlinx.android.synthetic.main.fragment_my.view.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException
import kotlin.math.exp

class MyFragment : Fragment() {

    private lateinit var explain: Button
    private lateinit var homePageActivity: HomePageActivity
    private lateinit var tv_User: TextView
    private lateinit var url: String

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        homePageActivity = activity as HomePageActivity
        val view = inflater.inflate(R.layout.fragment_my, container, false)
        init(view)
        initClick(view)
        initData()
        return view
    }

    private fun init(view: View) {
        explain = view.btn_explain
        tv_User = view.tv_user
        url = "${OkhttpUtils.url}item/create"
    }

    private fun initClick(view: View) {
        view.btn_actionSettings.setOnClickListener {
            SettingsActivity.actionStart(homePageActivity)
        }

        view.btn_actionAbout.setOnClickListener {
            AboutActivity.actionStart(homePageActivity)
        }
    }

    private fun initData() {

        OkhttpUtils.getAsync(url, object : DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {

            }

            override fun requestSuccess(result: String) {
                val doc = Jsoup.parse(result)
                //获取用户名
                val userName = doc.getElementById("avatar")!!.text()
                tv_User.text = userName


                //获取填写
                val content = doc.select("section section p").outerHtml()

                btn_explain.setOnClickListener {
                    AlertDialog.Builder(homePageActivity).apply {
                        setTitle("填写说明!")
                        setMessage(Html.fromHtml(content))
                        setCancelable(false)
                        setPositiveButton("我知道了") { _, _ -> }
                        create()
                        show()
                    }
                }
            }
        })
    }
}